package com.dq.controller;

import com.dq.keywordMatch.SensitiveWordInit;
import com.dq.keywordMatch.SensitivewordEngine;
import com.dq.keywordMatch.SmsSensitiveWord;
import com.dq.mapper.*;
import com.dq.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplyForGiftMapper applyForGiftMapper;
    @Autowired
    CareListMapper careListMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    CommentReplyMapper commentReplyMapper;
    @Autowired
    SensitiveWordInit sensitiveWordInit;

    @RequestMapping("/all")
    public String showAllGoods(Model model){
        List<Goods> goods = goodsMapper.getGoods();
        model.addAttribute("goods",goods);
        return "redirect:/";
    }

    @RequestMapping("/showAll")
    public String showAll(Model model){
        List<Goods> goods = goodsMapper.getGoods();
        model.addAttribute("goods",goods);
        List<Goods> recentGoods = goodsMapper.getRecentGoods();
        model.addAttribute("recentGoods",recentGoods);
        HashMap map = new HashMap();
        for (Goods good : goods) {
            int i = careListMapper.countByGoodId(good.getId());
            map.put(good.getId(),i);
        }
        model.addAttribute("careCount",map);
        return "/web1/showAll";
    }

    @RequestMapping("/good/{id}")
    public String showGoodById(@PathVariable("id") String id,Model model){

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();
        model.addAttribute("Id",username);

        Goods good = goodsMapper.getGoodById(id);
        model.addAttribute("good",good);
      //  model.addAttribute("delegateid",good.getDelegateId());
        User user = userMapper.getUserById(good.getDelegateId());
        model.addAttribute("userName",user.getName());

        List<Goods> recentGoods = goodsMapper.getRecentGoods();
        model.addAttribute("recentGoods",recentGoods);

        List<Comment> commentList = commentMapper.showCommentsByBlogId(id);
        model.addAttribute("commentList",commentList);
        HashMap map = new HashMap();
        HashMap mapReply = new HashMap();
        HashMap photoMap = new HashMap();
        for (Comment comment : commentList) {
            User userById = userMapper.getUserById(comment.getUserId());
            map.put(comment.getUserId(),userById.getName());
            List<CommentReply> commentReplies = commentReplyMapper.showCommentsReplyById(comment.getCommentId());
            mapReply.put(comment.getCommentId(),commentReplies);
            photoMap.put(comment.getUserId(),userById.getPhoto());
            for (CommentReply reply : commentReplies) {
                String userId = reply.getUserId();
                String replyUserId = reply.getReplyUserId();
                User userById1 = userMapper.getUserById(userId);
                User userById2 = userMapper.getUserById(replyUserId);
                map.put(userId,userById1.getName());
                map.put(replyUserId,userById2.getName());

            }
        }
        model.addAttribute("photoMap",photoMap);
        model.addAttribute("mapReply",mapReply);
        model.addAttribute("userNameMap",map);
        return "/web1/blog-details";
    }


    @RequestMapping("/toInsert")
    public String toInsertGood(){
        return "web1/insertGood";
    }

    @RequestMapping("/toGive")
    public String toGive(@RequestParam("gi")String gid,
                         @RequestParam("fi")String fid, Model model){

        User user = userMapper.getUserById(fid);
        model.addAttribute("user",user);
        model.addAttribute("goodId",gid);

        return "/web1/giveToKid";
    }

    @RequestMapping("/cs/{id}")
    public String comfirmSend(@PathVariable("id")String gid){
        Goods good = goodsMapper.getGoodById(gid);
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String fid = userDetails.getUsername();
        applyForGiftMapper.insertAFG(new ApplyForGift(gid,0,fid,good.getDelegateId()));
        goodsMapper.updateGoodById(gid);
        return "redirect:/";
    }

    @RequestMapping("/careList")
    public  String toCareList(Model model){
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String id = userDetails.getUsername();
        CareList care = careListMapper.getAllCaresById(id);
        if(care!=null){
            model.addAttribute("careGoods",care.getGoods());

        }else {
            model.addAttribute("msg","还没有任何关注哦！");
        }
        System.out.println(userDetails.getAuthorities());

        model.addAttribute("cares",care);

        return "/web1/care-list";
    }

    @RequestMapping("/addCare/{goodId}")
    public String addCare(@PathVariable("goodId")String goodId){
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String id = userDetails.getUsername();
        careListMapper.insertCare(id,goodId);
        return "redirect:/goods/showAll";
    }
    @RequestMapping("/deleteCare/{gid}")
    public String deleteCare(@PathVariable("gid")String gid){
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String id = userDetails.getUsername();
        careListMapper.deleteCareById(id,gid);
        return "redirect:/goods/careList";
    }

    @RequestMapping("/insert")
    public String insertGood(@RequestParam(value = "id",required = false) String id,
                             @RequestParam(value = "productName",required = false) String productName,
                             @RequestParam(value = "file",required = false) MultipartFile file,
                             @RequestParam(value = "description",required = false) String description,
                             @RequestParam(value = "price",required = false) String price) throws IOException {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String uid = userDetails.getUsername();

        String path = "D:/Allworkspace/ideaSPACE/mysign/src/main/resources/static/picture";
        System.out.println(path);
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        StringBuffer sb=new StringBuffer("/picture/");
        sb.append(file.getOriginalFilename());
        String picPath=sb.toString();

        file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
        goodsMapper.insertGood(new Goods(id,productName,picPath, description,Double.parseDouble(price),uid,new Date(),0));
        return "redirect:/";
    }


    @RequestMapping("/allBlogs")
    public String allBlogs(Model model){
        Map map = new HashMap();
        List<Goods> goods = goodsMapper.getGoods();
        model.addAttribute("goods",goods);
        for (Goods good : goods) {
            if(!map.containsKey(good.getDelegateId())){
                String name = userMapper.getUserById(good.getDelegateId()).getName();
                map.put(good.getDelegateId(),name);
            }
        }
        model.addAttribute("nameMap",map);
        return "/web1/allBlogs";
    }

    /**
     * 后台商品页面分页
     */
    @RequestMapping("/page")
    public String page(@RequestParam(value = "pageNo",required = false) String pageNumber,Model model){
        String spPage=pageNumber;
        //设置每页条数
        int pageSize=2;
        //页数
        int pageNo=0;
        if(spPage==null){
            pageNo=1;
        }else {
            pageNo = Integer.valueOf(spPage);
            if (pageNo < 1) {
                pageNo = 1;
            }
        }
        //设置最大页数
        int totalCount=0;
        int count=goodsMapper.getCount();
        if(count>0){
            totalCount=count;
        }
        int maxPage=totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
        if(pageNo>maxPage){
            pageNo=maxPage;
        }
        int  tempPageNo=(pageNo-1)*pageSize;

        Map map=new HashMap();
        map.put("pageNo",tempPageNo);
        map.put("pageSize",pageSize);

        List<Goods> goods=goodsMapper.getPartGoods(map);
        for (Goods good : goods) {

            if(!map.containsKey(good.getDelegateId())){
                String name = userMapper.getUserById(good.getDelegateId()).getName();
                map.put(good.getDelegateId(),name);
            }
        }
        model.addAttribute("nameMap",map);
        //最后把信息放入model转发到页面把信息带过去
        model.addAttribute("goods",goods);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("maxPage",maxPage);


        return "/web1/allBlogs";
    }

    @RequestMapping("/goodInfo")
    public String goodInfo(@RequestParam(value = "pageNo",defaultValue = "1")Integer page,Model model){
        if (page < 1) {
            page = 1;
        }
        int totalCount = 0;
        int count=goodsMapper.getGoods().size();
        if(count > 0){
            totalCount=count;
        }
        int maxPage=totalCount%1==0?totalCount/1:totalCount/1+1;
        if(page>maxPage){
            page=maxPage;
        }
        model.addAttribute("maxPage",maxPage);

        PageHelper.startPage(page,2);
        PageInfo<Goods> pageInfo = new PageInfo<Goods>(goodsMapper.getGoods());
        List<Goods> goods = pageInfo.getList();
        model.addAttribute("goods",goods);
        Map map = new HashMap<>();
        for (Goods good : goods) {
            if(!map.containsKey(good.getDelegateId())){
                String name = userMapper.getUserById(good.getDelegateId()).getName();
                map.put(good.getDelegateId(),name);
            }
        }
        List<Goods> recentGoods = goodsMapper.getRecentGoods();
        model.addAttribute("recentGoods",recentGoods);
        model.addAttribute("pageNo",page);
        model.addAttribute("nameMap",map);
        return "/web1/allBlogs";
    }

    @RequestMapping("/keyword")
    public String keyword(@RequestParam(value = "pageNo",defaultValue = "1")Integer page,Model model,String keyword){
        if (page < 1) {
            page = 1;
        }
        int totalCount = 0;
        int count=goodsMapper.getKeyGoods(keyword).size();
        if(count>0){
            totalCount=count;
        }
        int maxPage=totalCount%1==0?totalCount/1:totalCount/1+1;
        if(page>maxPage){
            page=maxPage;
        }
        model.addAttribute("maxPage",maxPage);
        PageHelper.startPage(page,1);
        PageInfo<Goods> pageInfo = new PageInfo<Goods>(goodsMapper.getKeyGoods(keyword));
        List<Goods> keyGoods = pageInfo.getList();
        model.addAttribute("keyGoods",keyGoods);
        Map map = new HashMap();
        for (Goods good : keyGoods) {
            if(!map.containsKey(good.getDelegateId())){
                String name = userMapper.getUserById(good.getDelegateId()).getName();
                map.put(good.getDelegateId(),name);
            }
        }
        List<Goods> recentGoods = goodsMapper.getRecentGoods();
        model.addAttribute("recentGoods",recentGoods);
        model.addAttribute("keyword",keyword);
        model.addAttribute("pageNo",page);
        model.addAttribute("nameMap",map);
        return "/web1/keywordBlogs";
    }

    @RequestMapping("/keyContent")
    public String  keyContent(@RequestParam(value = "pageNo",defaultValue = "1")Integer page,
                              @RequestParam(value = "keyContent",required = false)String keyContent
    ,Model model){
        List list1 = new ArrayList();
        list1.add(new SmsSensitiveWord(keyContent));
        Map map1 = sensitiveWordInit.initKeyWord(list1);
        List<Goods> list2 = new ArrayList<Goods>();
        for (Goods good : goodsMapper.getGoods()) {
            if (SensitivewordEngine.isContaintSensitiveWord(good.getDescription(),2)) {
                list2.add(good);
            }
        }
        Map map2 = new HashMap();
        for (Goods good : list2) {
            if(!map2.containsKey(good.getDelegateId())){
                String name = userMapper.getUserById(good.getDelegateId()).getName();
                map2.put(good.getDelegateId(),name);
            }
        }
        List<Goods> recentGoods = goodsMapper.getRecentGoods();
        model.addAttribute("recentGoods",recentGoods);
        model.addAttribute("nameMap",map2);
        model.addAttribute("keyGoods",list2);
        return "/web1/keyContentBlogs";
    }
}
